//
//  LXExtension+NSDate.swift
//  LXExtensions
//
//  Created by yoctech on 2021/10/8.
//

import Foundation

@objc public extension NSDate{
    
    /// 格式化字符串
    /// - Parameters:
    ///   - formart: 格式
    ///   - locale: 地区
    /// - Returns: 日期字符串
    @objc func lx_toString(_ formart:String = "yyyy-MM-dd", locale: Locale = .current) -> String{
        let formartter = DateFormatter.init()
        formartter.locale = locale
        formartter.dateFormat = formart
        return formartter.string(from: self as Date)
    }
    
    
    /// 日历
    @objc var lx_calendar: Calendar {
        Calendar.current
    }
    
    /// 当月天数
    @objc var lx_daysInMonth: Int {
        (self as Date).lx_daysInMonth
    }
    /// 星期几
    @objc var lx_weekday: Int {
        (self as Date).lx_weekday
    }
    /// 几号
    @objc var lx_day: Int {
        (self as Date).lx_day
    }

    
    /// 获取当前日期开头的日期
    /// - Parameter component: 开头的格式,年月日
    /// - Returns: 起始日期
    @objc func lx_beginning(of component: NSCalendar.Unit) -> NSDate? {
        if component == .day {
            return lx_calendar.startOfDay(for: self as Date) as NSDate
        }
        
        var components: Set<Calendar.Component> {
            switch component {
            case .second:
                return [.year, .month, .day, .hour, .minute, .second]
                
            case .minute:
                return [.year, .month, .day, .hour, .minute]
                
            case .hour:
                return [.year, .month, .day, .hour]
                
            case .weekOfYear, .weekOfMonth:
                return [.yearForWeekOfYear, .weekOfYear]
                
            case .month:
                return [.year, .month]
                
            case .year:
                return [.year]
                
            default:
                return []
            }
        }
        
        guard !components.isEmpty else { return nil }
        return lx_calendar.date(from: lx_calendar.dateComponents(components, from: self as Date)) as NSDate?
    }
    
    @objc func lx_byAdding(_ component: NSCalendar.Unit, value: Int) -> Date? {
        return (lx_calendar as NSCalendar).date(byAdding: component, value: value, to: self as Date)
    }
    
    /// 农历日期字符串
    /// - Parameter formatterString: 格式
    /// - Returns: 农历字符串
    @objc func lx_toLunarString(_ formatterString:String = "yyyyMMdd") -> String {
        return (self as Date).lx_toLunarString(formatterString)
    }

}
